package com.friday.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.friday.dao.ProductDao;
import com.friday.util.UploadImg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ProductController {

    @Autowired
    private ProductDao productDao;

    @RequestMapping("/productAdd")
    public JSONObject addProduct(@RequestBody JSONObject product){
        JSONObject result = new JSONObject();
        int tag = productDao.addProduct(product);
        if( tag > 0){
            result.put("result","success");
            result.put("product_id",product.getInteger("id"));
        }else {
            result.put("result","fail");
            result.put("product_id",null);
        }
        return result;
    }

    @RequestMapping("/productImgEdit")
    public String addImg(int id, MultipartFile file){
        String url=" http://imgdic.natapp1.cc"+ UploadImg.upload(file);
        JSONObject picture = new JSONObject();
        picture.put("id",id);
        picture.put("picture",url);
        int tag=productDao.editProduct(picture);
        if(tag>0)
            return "success";
        return "fail";
    }

    @RequestMapping("/productOnsaleList")
    public JSONArray getProductOnsale(){
        return productDao.getProductOnsale();
    }

    @RequestMapping("/productDetail")
    public JSONObject getProductById(@RequestParam("id") int id){
       JSONObject product = productDao.getProductById(id);
       product.put("storageData",productDao.getProdStockByPId(id));
       product.put("timeLine",productDao.getProdRecordByPId(id));
       product.put("salesData",productDao.getProdOutByPId(id));
       return product;
    }

    @RequestMapping("/productList")
    public JSONArray getAllProduct(){
        return productDao.getAllProduct();
    }

    @RequestMapping("/productEdit")
    public String editProduct(@RequestBody JSONObject product){
        product.remove("picture");
        int tag = productDao.editProduct(product);
        if(tag>0)
            return "success";
        return "fail";
    }

    @RequestMapping("/productDelete")
    public String delProductById(@RequestParam("id") int id){
        int tag = productDao.delProductById(id);
        if(tag>0)
            return "success";
        return "fail";

    }

}
